<?php
/**
 * JoosFish - Multi Lingual extention and translation manager for Joostina CMS
 * Copyright (C) 2011 Joostina Team
 * 
 * @name JoosFish
 * @copyright © 2011 Joostina team, © 2003-2007 Think Network GmbH, Munich
 * @license GNU General Public License version 2
 * @version 1.8.2.1
 * @package Joostina
 *
 * Based on the source code of Joom!Fish 1.8.2 copyrighted by Think
 * Network GmbH, Munich. The main contribution is made by developers of
 * Joom!Fish project, but the main reason behind making JoosFish an alongside
 * project is to maintain it's compatibility with Joostina CMS 1.3.x
 * 
 * For full copyright note see documetation/COPYRIGHT.php
 * 
 * For changes see documentation/CHANGELOG.php
 *
 * The "GNU General Public License" (GPL) is available at
 * http: *www.gnu.org/copyleft/gpl.html
 * -----------------------------------------------------------------------------
 * $Id:jfdatabase.systembot.php 580 2007-07-24 18:52:05Z akede $
 * @package joomfish
 * @subpackage system.jfdatabase_bot
 *
*/

/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

$_MAMBOTS->registerFunction( 'onStart', 'botJFDatabase' );
$_MAMBOTS->registerFunction( 'onAfterStart', 'botJFDiscoverLanguage' );
$_MAMBOTS->registerFunction( 'onAfterStart', 'botJFInitialize' );

global $mosConfig_absolute_path;

if (file_exists( $mosConfig_absolute_path . '/components/com_joomfish/joomfish.php' )) {
	require_once( $mosConfig_absolute_path . '/administrator/components/com_joomfish/mldatabase.class.php' );
	require_once( $mosConfig_absolute_path . '/administrator/components/com_joomfish/joomfish.class.php' );
	//require_once( $mosConfig_absolute_path '/components/com_joomfish/includes/joomfish.class.php' );
}

/**
* Exchange of the database abstraction layer for multi lingual translations.
*/
function botJFDatabase() {
	global $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix,$mosConfig_debug;

	$GLOBALS[ 'mosConfig_mbf_content' ] = '1';			// ToDo: Might need correction!!
	$GLOBALS[ 'mosConfig_multilingual_support' ] = 1;
	$database = new mlDatabase( $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix );
	$database->debug( $mosConfig_debug );

	// if running mysql 5, set sql-mode to mysql40 - thereby circumventing strict mode problems
	if ( strpos( $database->getVersion(), '5' ) === 0 ) {
		$query = "SET sql_mode = 'MYSQL40'";
		$database->setQuery( $query );
		$database->query();
	}

	$GLOBALS['database'] = $database;
	
	//Переопределяем свойство _db объекта $mainframe, (C)А.Геоня
	$mainframe = mosMainFrame::getInstance();
	$mainframe->_db = $database;
}

/** The function finds the language which is to be used for the user/session
 *
 * It is possible to choose the language based on the client browsers configuration,
 * the activated language of the configuration and the language a user has choosen in
 * the past. The decision of this order is done in the JoomFish configuration.
 *
 * The other topic while choosing the language is to change the $mosConfig_lang var
 * for the other CMT's and same this for the user in the session or cockie.
 */
function botJFDiscoverLanguage ( ) {
	global $mosConfig_lang, $database, $_MAMBOTS;
	$GLOBALS['mosConfig_defaultLang'] = $mosConfig_lang;        // Save the default language of the site

	// get instance of JoomFishManager to obtain active language list and config values
	$jfm =&  JoomFishManager::getInstance();

	// check if param query has previously been processed
	if ( !isset($_MAMBOTS->_system_mambot_params['jfSystembot']) ) {
		// load mambot params info
		$query = "SELECT params"
		. "\n FROM #__mambots"
		. "\n WHERE element = 'jfdatabase.systembot'"
		. "\n AND folder = 'system'"
		;
		$database->setQuery( $query );
		$database->loadObject($mambot);

		// save query to class variable
		$_MAMBOTS->_system_mambot_params['jfSystembot'] = $mambot;
	}

	// pull query data from class variable
	$mambot = $_MAMBOTS->_system_mambot_params['jfSystembot'];

	$botParams = new mosParameters( $mambot->params );
	$determitLanguage 		= $botParams->def( 'determitLanguage', 1 );
	$newVisitorAction		= $botParams->def( 'newVisitorAction', 'browser' );
	$use302redirect			= $botParams->def( 'use302redirect', 0 );
	$enableCookie			= $botParams->def( 'enableCookie', 1 );

	$client_lang = '';
	$lang_known = false;
	$jfcookie = mosGetParam( $_COOKIE, 'jfcookie', null );
	if (isset($jfcookie["lang"]) && $jfcookie["lang"] != "") {
		$client_lang = $jfcookie["lang"];
		$lang_known = true;
	}
	if (($lang = mosGetParam( $_GET, 'lang', '' )) ) {
		if( $lang != '' ) {
			$client_lang = $lang;
			$lang_known = true;
		}
	}
	if ( !$lang_known && $determitLanguage &&
				key_exists( 'HTTP_ACCEPT_LANGUAGE', $_SERVER ) && !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ) {

		switch ($newVisitorAction) {
			// usesing the first defined Joom!Fish language
			case 'joomfish':
				$activeLanguages = $jfm->getActiveLanguages();
				$keys = array_keys($activeLanguages);
				$client_lang = $activeLanguages[$keys[0]]->getLanguageCode();
				break;

			case 'site':
				$jfLang = jfLanguage::createByJoomla( $mosConfig_lang );
				$client_lang = $jfLang->getLanguageCode();
				break;

			// no language chooses - assume from browser configuration
			case 'browser':
			default:
				// language negotiation by Kochin Chang, June 16, 2004
				// retrieve active languages from database
				$active_iso = array();
				$active_isocountry = array();
				$active_code = array();
				$activeLanguages = $jfm->getActiveLanguages();
				if( count( $activeLanguages ) == 0 ) {
					return $mosConfig_lang;
				}

				foreach ($activeLanguages as $lang) {
					$active_iso[] = $lang->iso;
					if( preg_match('/[_-]/', $lang->iso) ) {
						$isocountry = split('[_-]',$lang->iso);
						$active_isocountry[] = $isocountry[0];
					}
					$active_code[] = $lang->shortcode;
				}

				// figure out which language to use - browser languages are based on ISO codes
				$browserLang = explode(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]);

				foreach( $browserLang as $lang ) {
					if( in_array($lang, $active_iso) ) {
						$client_lang = $lang;
						break;
					}
					$shortLang = substr( $lang, 0, 2 );
					if( in_array($shortLang, $active_isocountry) ) {
						$client_lang = $shortLang;
						break;
					}

					// compare with code
					if ( in_array($shortLang, $active_code) ) {
						$client_lang = $shortLang;
						break;
					}
				}
				break;
		}
	}

	// get the name of the language file for joomla
	$jfLang = jfLanguage::createByShortcode($client_lang, false);
	if( $jfLang === null ) {
		$jfLang = jfLanguage::createByISO( $client_lang, false );
	}

	if( !$lang_known && $use302redirect ) {
		// using a 302 redirect means that we do not change the language on the fly the first time, but with a clean reload of the page

		$href= "index.php";
		$hrefVars = '';
		$queryString = mosGetParam($_SERVER, 'QUERY_STRING', null);
		if( !empty($queryString) ) {
			$vars = explode( "&", $queryString );
			if( count($vars) > 0 && $queryString) {
				foreach ($vars as $var) {
					if( strpos('=', $var ) !== false ) {
						list($key, $value) = explode( "=", $var);
						if( $key != "lang" ) {
							if( $hrefVars != "" ) {
								$hrefVars .= "&amp;";
							}
							// ignore mosmsg to ensure it is visible in frontend
							if( $key != 'mosmsg' ) {
								$hrefVars .= "$key=$value";
							}
						}
					}
				}
			}
		}

		// Add the existing variables
		if( $hrefVars != "" ) {
			$href .= '?' .$hrefVars;
		}

		if( $jfLang->getLanguageCode() != null ) {
			$lang = 'lang=' .$jfLang->getLanguageCode();
		} else {
			// it's important that we add at least the basic parameter - as of the sef is adding the actual otherwise!
			$lang = 'lang=';
		}

		// if there are other vars we need to add a & otherwiese ?
		if( $hrefVars == '' ) {
			$href .= '?' . $lang;
		} else {
			$href .= '&amp;' . $lang;
		}
		$href = sefRelToAbs($href);

		$GLOBALS['iso_client_lang'] = $jfLang->getLanguageCode();
		header( 'HTTP/1.1 303 See Other' );
		header( "Location: ". sefRelToAbs($href) );
		exit();
	}

	if( isset($jfLang) && $jfLang->code != "" && ($jfLang->active  || $jfm->getCfg("frontEndPreview") )) {
		$mosConfig_lang = $jfLang->code;
	} else {
		$jfLang = jfLanguage::createByJoomla( $mosConfig_lang );
		if( !$jfLang->active ) {
			?>
			<div style="background-color: #c00; color: #fff">
				<p style="font-size: 1.5em; font-weight: bold; padding: 10px 0px 10px 0px; text-align: center; font-family: Arial, Helvetica, sans-serif;">
				Joom!Fish config error: Default language is inactive!<br />&nbsp;<br />
				Please check configuration, try to use first active language</p>
			</div>
			<?php
			$activeLanguages = $jfm->getActiveLanguages();
			if( count($activeLanguages) > 0 ) {
				$jfLang = $activeLanguages[0];
				$mosConfig_lang = $jfLang->code;
			} else {
				// No active language defined - using system default is only alternative!
			}
		}
		$client_lang = $jfLang->getLanguageCode();
	}

	// set locale for this ISO code
	setlocale(LC_TIME, $jfLang->iso);


	$overwriteGlobalConfig = $botParams->def( 'overwriteGlobalConfig', 0 );
	if( $overwriteGlobalConfig ) {
		// We should overwrite additional global variables based on the language parameter configuration
		$langParams = new mosParameters( $jfLang->params );
		foreach ($langParams->toArray() as $key => $value) {
			$GLOBALS['mosConfig_' .$key] =$value;
		}
	}

	if($enableCookie) {
		setcookie( "lang", "", time() - 1800, "/" );
		setcookie( "jfcookie", "", time() - 1800, "/" );
		setcookie( "jfcookie[lang]", $client_lang, time()+24*3600, '/' );
	}
	$GLOBALS['iso_client_lang'] = $client_lang;
}

/** This function initialize the Joom!Fish manager in order to have
 * easy access and prepare certain information.
 */
function botJFInitialize ( ) {
	$GLOBALS[ '_JOOMFISH_MANAGER'] =& JoomFishManager::getInstance();
}
?>